﻿using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
using System.Reflection;

namespace Common
{
    public class ModelCommon
    {
        /// <summary>
        /// Copies the object values.(将原对象的属性值复制到目标对象中具有相同名称的属性值中)
        /// </summary>
        /// <param name="sourceObj">The source obj.</param>
        /// <param name="targetObj">The target obj.</param>
        public static void CopyObjectValues(object sourceObj, object targetObj)
        {
            if (sourceObj == null)
            {
                return;
            }
            if (targetObj == null)
            {
                return;
            }
            Type sourceType = sourceObj.GetType();
            Type targetType = targetObj.GetType();

            PropertyInfo[] sourcePropertyInfos = sourceType.GetProperties();
            foreach (PropertyInfo sourcePInfo in sourcePropertyInfos)
            {
                PropertyInfo targetPInfo = targetType.GetProperty(sourcePInfo.Name);
                if (targetPInfo != null)
                {
                    object[] customAttributes = targetPInfo.GetCustomAttributes(typeof(WithAccessAttribute), false);
                    if (customAttributes.Length == 0)
                    {
                        continue;
                    }

                    object value = sourcePInfo.GetValue(sourceObj, null);
                    if (targetPInfo.CanWrite)
                    {
                        targetPInfo.SetValue(targetObj, value, null);
                    }
                }
            }
        }
    }
}
